package handler

import (
	"context"
	"gozero-microservices/gateway-api/internal/logic"
	"gozero-microservices/gateway-api/internal/types"
	"gozero-microservices/gateway-api/utils"
	"net/http"
	"strconv"

	"github.com/zeromicro/go-zero/rest/httpx"
)

/*
 +----------------------------------------------------------------------
 + Title        : RegionHandler
 + Author       : huwl
 + Version      : 1.0.0
 + Initial-Time : 2025-08-08
 + Last-time    : 这个文件最后修改的时间 + 修改人的名称
 + Desc         : 区域处理器
 +----------------------------------------------------------------------
*/

type RegionHandler struct {
	BaseHandler
}

/**
 * 详情
 *
 * @param uint16 Id ---------------------------必传,Id
 * @return json
 * @author huwl
 * @date 2025/10/22 10:15:55
 */
func (control *RegionHandler) Detail(w http.ResponseWriter, r *http.Request) {
	id, _ := strconv.Atoi(utils.DefaultQuery(r, "id", "0"))

	// 调用逻辑层
	regionLogic := logic.NewRegionLogicInstance(context.Background(), control.SvcCtx)
	result, err := regionLogic.Detail(uint16(id))
	if err != nil {
		control.BaseError(r, w, control.WithGrpcError(err))
		return
	}

	control.BaseSuccess(r, w, control.WithData(result))
}

/**
 * 列表
 *
 * @param uint16 Id ---------------------------非必传,Id
 * @param string Ids --------------------------非必传,Id支持多个
 * @param string Pid --------------------------非必传,父级Id
 * @param string Pids -------------------------非必传,父级Id支持多个
 * @param string Name -------------------------非必传,名称
 * @param uint8 Level -------------------------非必传,级别
 * @param string IsHot ------------------------非必传,是否热门
 * @param string SortField --------------------非必传,排序字段
 * @param string SortType ---------------------非必传,排序方式
 * @param int8 PageSize -----------------------非必传,条数
 * @param uint8 Page --------------------------非必传,页码
 * @return *common.RegionListResponse, error
 * @author huwl
 * @date 2025/10/22 10:15:55
 */
func (control *RegionHandler) List(w http.ResponseWriter, r *http.Request) {
	var req types.RegionQueryRequest
	if err := httpx.Parse(r, &req); err != nil {
		control.BaseError(r, w, control.WithMessage(err.Error()))
		return
	}

	// 调用逻辑层
	regionLogic := logic.NewRegionLogicInstance(context.Background(), control.SvcCtx)
	result, err := regionLogic.List(req)
	if err != nil {
		control.BaseError(r, w, control.WithGrpcError(err))
		return
	}

	control.BaseSuccess(r, w, control.WithData(map[string]interface{}{
		"page":       result.Page,
		"page_size":  result.PageSize,
		"total":      result.Total,
		"page_total": result.PageTotal,
		"regions":    result.Regions,
	}))
}
